<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { set } from "@/utils/index.ts";
import { login } from "@/api/user.ts";
import { Toast } from "vant";
import { useStore } from "vuex";
const store = useStore();

let form = ref();
const router = useRouter();
const user = ref({
  userName: "",
  passWord: "",
});

async function submit() {
  let msg = await form.value.validate();
  if (msg) return;
  login(user.value).then((res: any) => {
    if (res.code === 200) {
      set("token", res.token);
      set("userName", user.value.userName);
      store.commit("setUserName", user.value.userName);
      store.commit("setToken", res.token);
      router.push("/message");
    } else {
      Toast.fail(res.msg);
    }
  });
}
</script>

<template>
  <div class="container">
    <h2 class="title">登录</h2>
    <van-form ref="form">
      <van-cell-group inset>
        <van-field
          v-model="user.userName"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="user.passWord"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="submit"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
.title {
  text-align: center;
}
.container {
  height: 100%;
  padding: 20px;
}
</style>